//
//  BK_StoreOrderDetail_VC.m
//  bestkeep
//
//  Created by TOPTEAM on 2017/3/31.
//  Copyright © 2017年 utouu. All rights reserved.
//

#import "BK_StoreOrderDetail_VC.h"
#import "BK_SOD_Address_Cell.h"
#import "BK_SOD_Money_Cell.h"
#import "BK_SOD_List_Cell.h"
#import "BK_OD_Tool.h"
//#import "BK_SOD_Type_Cell.h"
#import <Masonry.h>
#import "BK_SP_OD_Model.h"

#import "BK_StoreOrder_Cell.h"
@interface BK_StoreOrderDetail_VC ()
<
UITableViewDelegate,
UITableViewDataSource
>
@property(nonatomic, strong)UITableView *tableView;
@property(nonatomic, strong)ExceptionView *exceptionView;
@property(nonatomic, strong)NSMutableArray*marr_Section;

@property(nonatomic, strong)BK_SP_OD_Model* model_OD;



@end

@implementation BK_StoreOrderDetail_VC
- (void)viewDidLoad {
    [super viewDidLoad];
    [self  setProperty];
    [self  createUI];
    [self  check_NetWork];
    
}
#pragma mark==================setProperty======================
-(void)setProperty{
    self.view .backgroundColor = [UIColor whiteColor];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.title = @"订单详情";
    if( ([[[UIDevice currentDevice] systemVersion] doubleValue]>=7.0)) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
        self.extendedLayoutIncludesOpaqueBars = NO;
        self.automaticallyAdjustsScrollViewInsets = NO;
        self.modalPresentationCapturesStatusBarAppearance = NO;
        self.navigationController.navigationBar.clipsToBounds = NO;
    }
    _marr_Section=[[NSMutableArray alloc]init];
    
}

#pragma mark==================createUI======================
-(void)createUI{
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    _tableView.backgroundColor = RGBACOLOR(242, 242, 242, 1);
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLineEtched;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
    [self.view addSubview:_tableView];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(self.view);
        make.top.mas_equalTo(self.view).offset(0);
        make.bottom.mas_equalTo(self.view.mas_bottom).offset(0);
    }];
    
}
#pragma mark==================checkNet======================
-(void)check_NetWork{
    RequestReachabilityStatus status = [RequestManager reachabilityStatus];
    switch (status) {
        case RequestReachabilityStatusReachableViaWiFi:
        case RequestReachabilityStatusReachableViaWWAN: {
            /*
             *  获取小店订单详情数据
             */
            [self get_BK_StoreOrderDetail_Data];
        }
            break;
        default: {
            [HUD dismiss];
            
            self.exceptionView = [ExceptionView exceptionViewWithType:ExceptionCodeTypeNoNetwork];
            ExceptionViewAction *action = [ExceptionViewAction actionWithType:ExceptionCodeTypeNoNetwork handler:^(ExceptionViewAction *action) {
                [self.exceptionView dismiss];
                self.exceptionView = nil;
                [self check_NetWork];
            }];
            [self.exceptionView addAction:action];
            [self.exceptionView showInView:self.view];
        }
            break;
    }
}
/*
 * 获取小店订单详情数据
 */
-(void)get_BK_StoreOrderDetail_Data{
    
    
    /*
     接口名称：	getStoreOrder
     接口用途：	获取小店订单详情
     method：	GET
     接口地址：	store/getOrder
     输入参数：
     key	参数类型	是否必须	参数解释
     orderNo	string	是	小店订单号
     返回数据：
     {
     "success": "true/false //成功/失败",
     "msg": "xxx //返回消息",
     "code": "xxx",
     "data":
     {
     "pay_way": "10:账户余额，20：支付宝，30：微信,支付方式",
     "pay_status": "支付状态 0：未支付，1:支付成功，2：支付失败",
     "pay_amount": "xxxx支付金额",
     "order_no": "xxxx订单号",
     "create_time": "下单时间",
     "discount_amount": "xxxx优惠金额",
     "store_address": "xxx小店地址",
     }
     }
     */
    
    NSString *const BKStoreGetOrder_URL      = @"store/getOrder";
    
    
    NSDictionary *paramDic =  @{@"orderNo" : _order_no};
    [BKIndicationView showInView:self.view];
    
    [[RequestManager manager] bkDataRequest:RequestMethodGet URLString:kOrderURL(BKStoreGetOrder_URL) parameters:paramDic success:^(id  _Nullable responseObject){
        [BKIndicationView dismiss];
        BOOL success = [responseObject[@"success"] boolValue];
        
        //        [---POST----Result----200--]:{"code":"","data":{"order_no":"20170410112346233229","store_address":"陕西省-西安市碑林区店","pay_amount":45,"pay_way":10,"create_time":"2017-04-10 11:23:45","pay_status":1,"discount_amount":0},"success":true,"msg":""}     --request.URL-->http://api.test.bestkeep.cn/store/getOrder?orderNo=20170410112346233229
        if (!success) {
            
            kOrderPromptMsg(responseObject[@"msg"]);
            //            return;
            
        }else{
            
            if ([responseObject[@"success"] boolValue]) {
                if(responseObject[@"data"]){
                    
                    _model_OD = [BK_SP_OD_Model  mj_objectWithKeyValues:responseObject[@"data"]];
                    
                    [self Create_Marr_Section];
                    
                }else{
                    self.exceptionView = [ExceptionView exceptionViewWithType:ExceptionCodeTypeNoData];
                    ExceptionViewAction *action = [ExceptionViewAction actionWithType:ExceptionCodeTypeNoData handler:^(ExceptionViewAction *action) {
                        [self.exceptionView dismiss];
                        self.exceptionView = nil;
                        [self get_BK_StoreOrderDetail_Data];
                    }];
                    [self.exceptionView addAction:action];
                    [self.exceptionView showInView:self.view];
                    
                }
                
            }else{
                
                /*
                 * 请求失败
                 */
                self.exceptionView = [ExceptionView exceptionViewWithType:ExceptionCodeTypeRequestFailed];
                ExceptionViewAction *action = [ExceptionViewAction actionWithType:ExceptionCodeTypeRequestFailed handler:^(ExceptionViewAction *action) {
                    [self.exceptionView dismiss];
                    self.exceptionView = nil;
                    [self get_BK_StoreOrderDetail_Data];
                }];
                [self.exceptionView addAction:action];
                [self.exceptionView showInView:self.view];
                
            }
            
        }
        
        
    }failure:^(id  _Nullable responseObject, NSError * _Nullable error){
        [BKIndicationView dismiss];
        NSString *errorMsg;
        if (error.code == -1001) {
            errorMsg = @"请求超时";
        }else if(error.code == 502){
            errorMsg = @"服务器开小差了，请稍后再试！";
        }else{
            errorMsg = @"请求失败";
        }
        kOrderPromptMsg(errorMsg);
        
    }];
    
}


/*
 * 获取小店订单详情数据
 */
-(void)Create_Marr_Section{
    //    NSMutableArray * marr_Cells=[[NSMutableArray alloc]init];
    
    
    CellModel* model0 =[[CellModel alloc]init];
    model0.reuseIdentifier = NSStringFromClass([BK_SOD_Address_Cell class]);
    model0.className=NSStringFromClass([BK_SOD_Address_Cell class]);
    model0.height = [BK_SOD_Address_Cell computeHeight:nil];
    model0.selectionStyle=UITableViewCellSelectionStyleNone;
    model0.accessoryType=UITableViewCellAccessoryNone;
    //    [marr_Cells addObject:model0];
    
    CellModel* model1 =[[CellModel alloc]init];
    model1.reuseIdentifier = NSStringFromClass([BK_SOD_Money_Cell class]);
    model1.className=NSStringFromClass([BK_SOD_Money_Cell class]);
    model1.height = [BK_SOD_Money_Cell computeHeight:nil];
    model1.selectionStyle=UITableViewCellSelectionStyleNone;
    model1.accessoryType=UITableViewCellAccessoryNone;
    //    [marr_Cells addObject:model1];
    
    
    CellModel* model2 =[[CellModel alloc]init];
    model2.reuseIdentifier = NSStringFromClass([BK_SOD_List_Cell class]);
    model2.className=NSStringFromClass([BK_SOD_List_Cell class]);
    model2.height = [BK_SOD_List_Cell computeHeight:nil];
    model2.selectionStyle=UITableViewCellSelectionStyleNone;
    model2.accessoryType=UITableViewCellAccessoryNone;
    //    [marr_Cells addObject:model2];
    
  
    
    
    
    
    /*
     * 地址段
     */
    SectionModel *model_Section0=[SectionModel sectionModelWithTitle:@"" cells:@[model0]];
    model_Section0.headerhHeight=1;
    model_Section0.footerHeight=1;
    [_marr_Section addObject:model_Section0];
    
    
    /*
     * 详情段
     */
    SectionModel *model_Section1=[SectionModel sectionModelWithTitle:@"" cells:@[model1]];
    model_Section1.headerhHeight=0.0001;
    model_Section1.footerHeight=1;
    [_marr_Section addObject:model_Section1];
    
    
    /*
     * 列表段
     */
    SectionModel *model_Section2=[SectionModel sectionModelWithTitle:@"" cells:@[model2]];
    model_Section2.headerhHeight=0.0001;
    model_Section2.footerHeight=1;
    [_marr_Section addObject:model_Section2];
    
    

    
    [_tableView reloadData];
    
    
  
}

#pragma mark tableView 代理相关
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _marr_Section.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    SectionModel *sm = _marr_Section[section];
    return sm.cells.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    SectionModel *sm = _marr_Section[section];
    
    NSLog(@"sm.headerhHeight-->%f",sm.headerhHeight);
    
    return sm.headerhHeight;
    
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    SectionModel *sm = _marr_Section[section];
    
    NSLog(@"sm.footerHeight-->%f",sm.footerHeight);
    
    return sm.footerHeight;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return nil;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    SectionModel *sm = _marr_Section[indexPath.section];
    CellModel *cm = sm.cells[indexPath.row];
    
    return cm.height;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    SectionModel *sm = _marr_Section[indexPath.section];
    CellModel *cm = sm.cells[indexPath.row];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cm.reuseIdentifier];
    if (!cell) {
        cell = [[NSClassFromString(cm.className) alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cm.reuseIdentifier];
    }
    cell.selectionStyle = cm.selectionStyle;
    
    if ([cm.className isEqualToString:NSStringFromClass([BK_SOD_Address_Cell class])]) {
        BK_SOD_Address_Cell *ex_cell=(BK_SOD_Address_Cell *)cell;
        [ex_cell relayOutUIWithModel:_model_OD];
    }
    
    
    
    if ([cm.className isEqualToString:NSStringFromClass([BK_SOD_Money_Cell class])]) {
        BK_SOD_Money_Cell *ex_cell=(BK_SOD_Money_Cell *)cell;
        [ex_cell relayOut_UI:_model_OD];
        
    }
    
    if ([cm.className isEqualToString:NSStringFromClass([BK_SOD_List_Cell class])]) {
        BK_SOD_List_Cell *ex_cell=(BK_SOD_List_Cell *)cell;
        [ex_cell relayOutUIWithModel:_model_OD];
        
    }
    

    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
